package com.ylsk.web.controller.system;

import com.ylsk.common.annotation.Anonymous;
import com.ylsk.common.core.domain.AjaxResult;
import com.ylsk.common.enums.FileSystemTypeEnum;
import com.ylsk.system.domain.BusinessFile;
import com.ylsk.system.domain.FileInfo;
import com.ylsk.system.domain.FileSimple;
import com.ylsk.system.mapper.SysApkPackageMapper;
import com.ylsk.system.service.IMinioFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;


/**
 * 文件管理控制层
 * @author ysy
 * @date 2023-08-04
 */

@CrossOrigin
@RestController
@RequestMapping("/system/file")
@Api(value = "FileManageController", tags = "4 图片文件管理", description = "4 图片文件管理",position = 1)
public class FileManageController
{

    @Autowired
    private IMinioFileService minioFileService;

    @Autowired
    private SysApkPackageMapper sysApkPackageMapper;

    /**
     * 图片上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    @ApiOperation(value = "图片文件管理-图片/文件上传", notes = "图片文件管理-图片/文件上传")
    public AjaxResult upload(@RequestParam("file") MultipartFile file) throws Exception {
        String systemType = "业务附件";
        FileSimple fileSimple =minioFileService.upload(file, FileSystemTypeEnum.BUSINESS_FILE.getCode());
        return AjaxResult.success(fileSimple);
    }

    @RequestMapping("/download")
    public void downloadFile(Long fileId, HttpServletResponse response) {

        InputStream inputStream   = null;
        OutputStream outputStream = null;
        try {
            if(null == fileId) {
                response.setHeader("Content-type", "text/html;charset=UTF-8");
                String data = "文件下载失败";
                OutputStream ps = response.getOutputStream();
                ps.write(data.getBytes("UTF-8"));
                return;
            }

            FileSimple fileSimple = minioFileService.getFile(fileId);

            outputStream = response.getOutputStream();
            // 获取文件对象
            inputStream = minioFileService.getInputStreamFile(fileId,fileSimple.getFilePath());
            byte buf[] = new byte[1024];
            int length = 0;
            response.reset();
            response.setHeader("Content-Disposition", "attachment;filename=" +
                    URLEncoder.encode(fileSimple.getFileName().substring(fileSimple.getFileName().lastIndexOf("/") + 1), "UTF-8"));
            response.setContentType("application/octet-stream");
            response.setCharacterEncoding("UTF-8");
            // 输出文件
            while ((length = inputStream.read(buf)) > 0) {
                outputStream.write(buf, 0, length);
            }
            inputStream.close();
        } catch (Throwable ex) {
            response.setHeader("Content-type", "text/html;charset=UTF-8");
            String data = "文件下载失败";
            try {
                OutputStream ps = response.getOutputStream();
                ps.write(data.getBytes("UTF-8"));
            }catch (IOException e){
                e.printStackTrace();
            }
        } finally {
            try {
                outputStream.close();
                if (inputStream != null) {
                    inputStream.close();
                }}catch (IOException e){
                e.printStackTrace();
            }
        }
    }

    /**
     * 删除文件
     * @param file
     * @return
     */
    @PostMapping("/removeFile")
    @ApiOperation(value = "图片文件管理-删除文件", notes = "图片文件管理-删除文件")
    public AjaxResult removeFile(FileInfo file) throws Exception {
        return AjaxResult.success(minioFileService.removeFile(file));
    }

    /**
     * 预览文件
     * @param file
     * @return
     */
    @PostMapping("/getFileUrl")
    @ApiOperation(value = "预览文件", notes = "预览文件")
    public AjaxResult getFileUrl(FileInfo file) throws Exception {
        return AjaxResult.success(minioFileService.getFileUrl(file));
    }

    /**
     * 根据业务数据id 获取业务数据附件
     * @param businessId
     * @return
     */
    @GetMapping("/getFileListByBusinessId/{businessId}")
    @ApiOperation(value = "获取业务数据附件信息", notes = "获取业务数据附件信息")
    public AjaxResult getFileListByBusinessId(@PathVariable("businessId")  Long businessId) throws Exception {
        return AjaxResult.success(minioFileService.getFileListByBusinessId(businessId));
    }

    /**
     * 单个附件详情
     * @param fileId
     * @return
     */
    @GetMapping("/getFile/{fileId}")
    @ApiOperation(value = "单个文件", notes = "单个文件")
    public AjaxResult getFile(@PathVariable("fileId")  Long fileId) throws Exception {
        return AjaxResult.success(minioFileService.getFile(fileId));
    }

    /**
     * 移动端apk 下载 放开下载链接
     * @param fileId
     * @param response
     */
    @Anonymous
    @GetMapping("/apk-download")
    public void apkDownload(Long fileId, HttpServletResponse response) {
        if(null == fileId){
            BusinessFile lastUpdatePackage = sysApkPackageMapper.getLastUpdatePackage();
            fileId = lastUpdatePackage.getFileId();
        }
        downloadFile(fileId,response);
    }
}


